<template>
  <div class="version-container">
    <el-card class="search-card">
      <el-form :model="formInline" label-width="100px" inline>
        <el-form-item label="版本类型">
          <el-select v-model="formInline.verSionType" placeholder="请选择版本类型" clearable style="width: 160px;">
            <el-option label="用户端" value="user" />
            <el-option label="商家端" value="merchant" />
          </el-select>
        </el-form-item>
        <el-form-item label="AppId">
          <el-input v-model="formInline.appId" placeholder="请输入AppId" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">查询</el-button>
          <el-button @click="clear">重置</el-button>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-card">
      <el-table
        :data="tableData"
        v-loading="loading"
        border
        style="width: 100%"
      >
        <el-table-column prop="id" label="版本ID" width="80" />
        <el-table-column prop="appName" label="应用名称" width="120">
          <template #default="scope">
            <el-tag :type="scope.row.appName === 'user' ? 'primary' : 'success'">
              {{ scope.row.appName === 'user' ? '用户端' : '商家端' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="platform" label="平台类型" width="100" />
        <el-table-column prop="versionCode" label="版本号" width="120" />
        <el-table-column prop="versionNum" label="版本数字" width="100" />
        <el-table-column prop="downloadUrl" label="下载地址" show-overflow-tooltip />
        <el-table-column prop="releaseStatus" label="发布状态" width="120">
          <template #default="scope">
            <el-tag :type="getReleaseStatusType(scope.row.releaseStatus)">
              {{ getReleaseStatusLabel(scope.row.releaseStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="releaseTime" label="发布时间" width="180">
          <template #default="scope">
            {{ scope.row.releaseTime || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="minSupportedVersion" label="最低支持版本" width="120" />
        <el-table-column prop="fileSize" label="安装包大小" width="120" />
        <el-table-column prop="fileHash" label="文件哈希值" show-overflow-tooltip />
        <el-table-column prop="createdAt" label="创建时间" width="180" />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
            <el-button size="small" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-scroll-wrapper">
        <div class="pagination-container">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          />
        </div>
      </div>
    </el-card>



    <!-- 新增版本弹窗 -->
    <el-dialog 
      title="新增版本" 
      v-model="addDialogVisible" 
      width="600px"
      @close="handleAddDialogClose"
    >
      <el-form :model="addFormData" label-width="120px" ref="addFormRef">
        <el-form-item label="应用名称" prop="appName">
          <el-select v-model="addFormData.appName" placeholder="请选择应用名称" style="width: 100%">
            <el-option label="用户端" value="user" />
            <el-option label="商家端" value="merchant" />
          </el-select>
        </el-form-item>
        <el-form-item label="平台类型" prop="platform">
          <el-select v-model="addFormData.platform" placeholder="请选择平台类型" style="width: 100%">
            <el-option label="iOS" value="ios" />
            <el-option label="Android" value="android" />
          </el-select>
        </el-form-item>
        <el-form-item label="版本号" prop="versionCode">
          <el-input v-model="addFormData.versionCode" placeholder="如：1.2.3" />
        </el-form-item>
        <el-form-item label="版本数字" prop="versionNum">
          <el-input v-model.number="addFormData.versionNum" placeholder="如：120(对应1.2.0)" />
        </el-form-item>
        <el-form-item label="最低支持版本" prop="minSupportedVersion">
          <el-input v-model="addFormData.minSupportedVersion" placeholder="最低支持的旧版本号" />
        </el-form-item>
        <el-form-item label="强制更新版本" prop="forceUpdateVersion">
          <el-input v-model="addFormData.forceUpdateVersion" placeholder="小于此版本需强制更新" />
        </el-form-item>
        <el-form-item label="下载地址" prop="downloadUrl">
          <el-input v-model="addFormData.downloadUrl" placeholder="请输入下载地址" />
        </el-form-item>
        <el-form-item label="是否强制更新" prop="isForceUpdate">
          <el-switch
            v-model="addFormData.isForceUpdate"
            :active-value="true"
            :inactive-value="false"
          />
        </el-form-item>
        <el-form-item label="安装包大小" prop="fileSize">
          <el-input v-model.number="addFormData.fileSize" placeholder="安装包大小(字节)" />
        </el-form-item>
        <el-form-item label="文件哈希值" prop="fileHash">
          <el-input v-model="addFormData.fileHash" placeholder="文件哈希值" />
        </el-form-item>
        <el-form-item label="发布状态" prop="releaseStatus">
          <el-select v-model="addFormData.releaseStatus" placeholder="请选择发布状态" style="width: 100%">
            <el-option label="草稿" value="draft" />
            <el-option label="测试中" value="testing" />
            <el-option label="已发布" value="published" />
            <el-option label="已归档" value="archived" />
          </el-select>
        </el-form-item>
        <el-form-item label="发布时间" prop="releaseTime">
          <el-date-picker
            v-model="addFormData.releaseTime"
            type="datetime"
            placeholder="请选择发布时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="版本更新说明" prop="releaseNotes">
          <el-input
            v-model="addFormData.releaseNotes"
            type="textarea"
            :rows="4"
            placeholder="版本更新说明"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAddForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑版本弹窗 -->
    <el-dialog 
      title="编辑版本" 
      v-model="editDialogVisible" 
      width="600px"
      @close="handleEditDialogClose"
    >
      <el-form :model="editFormData" label-width="120px" ref="editFormRef">
        <el-form-item label="版本ID">
          <el-input v-model="editFormData.id" disabled />
        </el-form-item>
        <el-form-item label="应用名称" prop="appName">
          <el-select v-model="editFormData.appName" placeholder="请选择应用名称" style="width: 100%">
            <el-option label="用户端" value="user" />
            <el-option label="商家端" value="merchant" />
          </el-select>
        </el-form-item>
        <el-form-item label="平台类型" prop="platform">
          <el-select v-model="editFormData.platform" placeholder="请选择平台类型" style="width: 100%">
            <el-option label="iOS" value="ios" />
            <el-option label="Android" value="android" />
          </el-select>
        </el-form-item>
        <el-form-item label="版本号" prop="versionCode">
          <el-input v-model="editFormData.versionCode" placeholder="如：1.2.3" />
        </el-form-item>
        <el-form-item label="版本数字" prop="versionNum">
          <el-input v-model.number="editFormData.versionNum" placeholder="如：120(对应1.2.0)" />
        </el-form-item>
        <el-form-item label="最低支持版本" prop="minSupportedVersion">
          <el-input v-model="editFormData.minSupportedVersion" placeholder="最低支持的旧版本号" />
        </el-form-item>
        <el-form-item label="强制更新版本" prop="forceUpdateVersion">
          <el-input v-model="editFormData.forceUpdateVersion" placeholder="小于此版本需强制更新" />
        </el-form-item>
        <el-form-item label="下载地址" prop="downloadUrl">
          <el-input v-model="editFormData.downloadUrl" placeholder="请输入下载地址" />
        </el-form-item>
        <el-form-item label="是否强制更新" prop="isForceUpdate">
          <el-switch
            v-model="editFormData.isForceUpdate"
            :active-value="true"
            :inactive-value="false"
          />
        </el-form-item>
        <el-form-item label="安装包大小" prop="fileSize">
          <el-input v-model.number="editFormData.fileSize" placeholder="安装包大小(字节)" />
        </el-form-item>
        <el-form-item label="文件哈希值" prop="fileHash">
          <el-input v-model="editFormData.fileHash" placeholder="文件哈希值" />
        </el-form-item>
        <el-form-item label="发布状态" prop="releaseStatus">
          <el-select v-model="editFormData.releaseStatus" placeholder="请选择发布状态" style="width: 100%">
            <el-option label="草稿" value="draft" />
            <el-option label="测试中" value="testing" />
            <el-option label="已发布" value="published" />
            <el-option label="已归档" value="archived" />
          </el-select>
        </el-form-item>
        <el-form-item label="发布时间" prop="releaseTime">
          <el-date-picker
            v-model="editFormData.releaseTime"
            type="datetime"
            placeholder="请选择发布时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="editFormData.createdAt"
            type="datetime"
            placeholder="创建时间"
            disabled
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="更新时间">
          <el-date-picker
            v-model="editFormData.updatedAt"
            type="datetime"
            placeholder="更新时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="版本更新说明" prop="releaseNotes">
          <el-input
            v-model="editFormData.releaseNotes"
            type="textarea"
            :rows="4"
            placeholder="版本更新说明"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEditForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { VersionService } from '@/api/versionApi'
import { GetAppVersionParams, AppVersion } from '@/api/model/appVersionModel'

// 表单数据
const formInline = ref({
  verSionType: '',
  appId: ''
})

// 表格数据
const tableData = ref<AppVersion[]>([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)



// 新增弹窗相关
const addDialogVisible = ref(false)
const addFormData = ref<AppVersion>({
  id: 0,
  appName: '',
  platform: '',
  versionCode: '',
  versionNum: 0,
  minSupportedVersion: '',
  forceUpdateVersion: '',
  downloadUrl: '',
  releaseNotes: '',
  isForceUpdate: false,
  fileSize: 0,
  fileHash: '',
  releaseStatus: '',
  releaseTime: '',
  createdAt: '',
  updatedAt: ''
})

// 编辑弹窗相关
const editDialogVisible = ref(false)
const editFormData = ref<AppVersion>({
  id: 0,
  appName: '',
  platform: '',
  versionCode: '',
  versionNum: 0,
  minSupportedVersion: '',
  forceUpdateVersion: '',
  downloadUrl: '',
  releaseNotes: '',
  isForceUpdate: false,
  fileSize: 0,
  fileHash: '',
  releaseStatus: '',
  releaseTime: '',
  createdAt: '',
  updatedAt: ''
})

const addFormRef = ref<InstanceType<typeof ElForm>>()
const editFormRef = ref<InstanceType<typeof ElForm>>()

// 搜索
const search = () => {
  currentPage.value = 1
  getVersionListData()
}

// 清空搜索条件
const clear = () => {
  formInline.value = {
    verSionType: '',
    appId: ''
  }
  currentPage.value = 1
  getVersionListData()
}

// 新增版本
const handleAdd = () => {
  // 重置表单数据
  addFormData.value = {
    id: 0,
    appName: '',
    platform: '',
    versionCode: '',
    versionNum: 0,
    minSupportedVersion: '',
    forceUpdateVersion: '',
    downloadUrl: '',
    releaseNotes: '',
    isForceUpdate: false,
    fileSize: 0,
    fileHash: '',
    releaseStatus: '',
    releaseTime: '',
    createdAt: '',
    updatedAt: ''
  }
  addDialogVisible.value = true
}

// 删除
const handleDelete = (row: AppVersion) => {
  ElMessageBox.confirm('确定要删除该版本吗？', '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    VersionService.deleteAppVersion(row.id)
      .then((res: any) => {
        if (res.code === '200') {
          ElMessage.success('删除成功')
          // 重新加载列表
          getVersionListData()
        } else {
          ElMessage.error(res.msg || '删除失败')
        }
      })
      .catch(() => {
        ElMessage.error('删除失败')
      })
  }).catch(() => {
    // 取消删除
  })
}

// 编辑
const handleEdit = (row: AppVersion) => {
  // 将行数据复制到编辑表单数据中
  Object.assign(editFormData.value, row)
  // 显示编辑弹窗
  editDialogVisible.value = true
}

// 处理分页大小变化
const handleSizeChange = (val: number) => {
  pageSize.value = val
  getVersionListData()
}

// 处理当前页变化
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  getVersionListData()
}

// 获取版本列表
const getVersionListData = () => {
  loading.value = true
  const params: GetAppVersionParams = {
    verSionType: formInline.value.verSionType,
    appId: formInline.value.appId ? parseInt(formInline.value.appId) : undefined,
    pageNum: currentPage.value,
    pageSize: pageSize.value
  }

  VersionService.getAppVersionPage(params)
    .then((res: any) => {
      if (res.code === '200') {
        tableData.value = res.data.list || []
        total.value = res.data.total || 0
      } else {
        ElMessage.error(res.msg || '获取版本列表失败')
      }
      loading.value = false
    })
    .catch(() => {
      loading.value = false
      ElMessage.error('获取版本列表失败')
    })
}

// 提交新增表单
const submitAddForm = async () => {
  if (!addFormRef.value) return
  
  await addFormRef.value.validate((valid) => {
    if (valid) {
      // 设置创建时间和更新时间
      const now = new Date().toISOString()
      addFormData.value.createdAt = now
      addFormData.value.updatedAt = now
      
      VersionService.addAppVersion(addFormData.value)
        .then((res: any) => {
          if (res.code === '200') {
            ElMessage.success('新增版本成功')
            addDialogVisible.value = false
            // 重新加载列表
            getVersionListData()
          } else {
            ElMessage.error(res.msg || '新增版本失败')
          }
        })
        .catch(() => {
          ElMessage.error('新增版本失败')
        })
    }
  })
}

// 提交编辑表单
const submitEditForm = () => {
  editFormRef.value?.validate((valid) => {
    if (valid) {
      VersionService.updateAppVersion(editFormData.value)
        .then(() => {
          ElMessage.success('编辑成功')
          editDialogVisible.value = false
          getVersionListData()
        })
        .catch(() => {
          ElMessage.error('编辑失败')
        })
    }
  })
}

// 获取发布状态标签类型
const getReleaseStatusType = (status: string) => {
  switch (status) {
    case 'draft': return 'info'
    case 'testing': return 'warning'
    case 'published': return 'success'
    case 'archived': return 'danger'
    default: return 'info'
  }
}

// 获取发布状态标签文本
const getReleaseStatusLabel = (status: string) => {
  switch (status) {
    case 'draft': return '草稿'
    case 'testing': return '测试中'
    case 'published': return '已发布'
    case 'archived': return '已归档'
    default: return status
  }
}

// 新增弹窗关闭事件
const handleAddDialogClose = () => {
  // 重置表单验证
  if (addFormRef.value) {
    addFormRef.value.resetFields()
  }
}

// 编辑弹窗关闭事件
const handleEditDialogClose = () => {
  // 重置表单验证
  if (editFormRef.value) {
    editFormRef.value.resetFields()
  }
}

onMounted(() => {
  getVersionListData()
})
</script>

<style scoped>
.version-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-top: 20px;
}

/* 分页容器基础样式 */
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  min-width: max-content;
  box-sizing: content-box;
}

/* 分页滚动容器增强样式 */
.pagination-scroll-wrapper {
  width: 100%;
  overflow-x: auto !important;
  overflow-y: hidden !important;
  -webkit-overflow-scrolling: touch !important;
  padding-bottom: 15px !important;
  margin: 0 !important;
  position: relative !important;
  z-index: 10 !important;
  flex: none;
  box-sizing: border-box;
}

/* 确保分页滚动容器的父元素不限制其显示 */
.pagination-scroll-wrapper,
.pagination-scroll-wrapper > * {
  transform: translateZ(0);
  will-change: transform;
}

/* 自定义滚动条 */
.pagination-scroll-wrapper::-webkit-scrollbar {
  height: 4px;
}

.pagination-scroll-wrapper::-webkit-scrollbar-track {
  background-color: #f0f0f0;
  border-radius: 2px;
}

.pagination-scroll-wrapper::-webkit-scrollbar-thumb {
  background-color: #c0c4cc;
  border-radius: 2px;
}

.pagination-scroll-wrapper::-webkit-scrollbar-thumb:hover {
  background-color: #909399;
}

/* 移动端特殊处理 */
@media (max-width: 768px) {
  .pagination-scroll-wrapper {
    padding-bottom: 20px !important;
    padding-left: 0 !important;
    padding-right: 0 !important;
  }
  
  .pagination-container {
    padding-left: 15px !important;
    padding-right: 15px !important;
    margin-left: 0 !important;
    margin-right: 0 !important;
  }
  
  /* 简化移动端分页布局，确保所有元素可见 */
  .el-pagination {
    min-width: 100% !important;
    padding-left: 0 !important;
    padding-right: 0 !important;
  }
  
  .el-pagination__total {
    min-width: 60px;
    flex-shrink: 0;
  }
  
  .el-pagination__sizes {
    min-width: 100px;
    flex-shrink: 0;
  }
}

.content-preview {
  border: 1px solid #ebeef5;
  min-height: 200px;
  padding: 10px;
  border-radius: 4px;
  background-color: #f5f7fa;
}
</style>